using System;
using System.Web;
using newtelligence.DasBlog.Runtime;
using newtelligence.DasBlog.Web.Services.Rss20;
using System.Xml;
using System.Xml.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;

namespace newtelligence.DasBlog.Web.Services
{
	/// <summary>
	/// Summary description for CommentAPI.
	/// </summary>
    public partial class WebWebServices
	{
        [OperationContract, XmlSerializerFormat, WebInvoke(Method="POST", UriTemplate="/comment?guid={guid}")]
        public void CommentApi( string guid, RssItem item )
        {
            try
            {
				Entry entry = dataService.GetEntry(guid);

				if (entry != null && DasBlog.Web.Core.Utils.AreCommentsAllowed(entry, SiteConfig.GetSiteConfig()))
				{
					Comment c = new Comment();
					c.InitializeNewEntry();
					foreach( XmlElement el in item.anyElements )
					{
						if ( el.NamespaceURI == "http://purl.org/dc/elements/1.1/" &&
							el.LocalName == "creator")
						{
							c.Author = el.InnerText;
							break;
						}
					}
					c.AuthorEmail = item.Author;
					c.AuthorHomepage = item.Link;
					c.AuthorIPAddress = HttpContext.Current.Request.UserHostAddress;
					c.Content = HttpContext.Current.Server.HtmlEncode(item.Description);
					c.TargetEntryId = entry.EntryId;
					c.TargetTitle = "";
					dataService.AddComment(c);
					
					// TODO: no comment mail?

					// break the caching
					HttpRuntime.Cache.Remove("BlogCoreData");
                    WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.OK;
                    WebOperationContext.Current.OutgoingResponse.SuppressEntityBody = true;
				}
				else if (entry != null && !entry.AllowComments)
				{
                    WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Forbidden;
                    WebOperationContext.Current.OutgoingResponse.SuppressEntityBody = true;
				}
				else if (entry == null)
				{
                    WebOperationContext.Current.OutgoingResponse.SetStatusAsNotFound();
                    WebOperationContext.Current.OutgoingResponse.SuppressEntityBody = true;
				}
            }
            catch(Exception exc)
            {
                ErrorTrace.Trace(System.Diagnostics.TraceLevel.Error,exc);
            }
        }
	}
}
